﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Threading;

namespace FlashGames
{
  public partial class SiteCreator : UserControl
  {
    FlashGames flashGames = new FlashGames();
    Object SelectedObject = new Object();
    FlashUnityPlayer.Player player;

    public static TextBox SelectedTextBox;
    public static string PageData;
    public Site SelectedSite;

    public string BaseUrl;
    public string Title;
    public string Desc;
    public string Image;

    public SiteCreator()
    {
      InitializeComponent();
      GetSiteList();
      GameFolderText.Text = flashGames.GameFolderPath;
      InsertSelectorOptions();
    }

    public bool DoSiteVailidationChecK()
    {
      if (!String.IsNullOrEmpty(SiteNameText.Text) && !String.IsNullOrEmpty(SiteUrlText.Text)
          && !String.IsNullOrEmpty(SiteDescriptionText.Text))
        return true;
      else return false;
    }

    private void SiteUrl_Leave(object sender, EventArgs e)
    {
      if (SiteSelectButton.SelectedIndex == 0)
      {
        Cursor.Current = Cursors.WaitCursor;
        Site site = (Site)SiteSelectButton.SelectedItem;
        if (site.Url != SiteUrlText.Text)
          try
          {
            BaseUrl = SiteUrlText.Text;
            Util.WebClient.BaseAddress = BaseUrl;
            PageData = Util.WebClient.DownloadString(BaseUrl);
            HtmlViewText.Navigate(Util.ResolvedUrl(BaseUrl,""));
            Match m = Regex.Match(PageData, @"(name|title)""\scontent=""(?<title>[^""]*)""", RegexOptions.IgnoreCase);
            if (m.Groups["title"].Success)
            {
              Title = Regex.Replace(m.Groups["title"].Value, @"\s+", " ", RegexOptions.IgnoreCase);
              if (!string.IsNullOrEmpty(Title))
                SiteNameText.Text = Title;
            }
            else
            {
              Match m1 = Regex.Match(PageData, @"<title>(?<title>[^<]*)</title>", RegexOptions.IgnoreCase);
              if (m1.Groups["title"].Success)
              {
                Title = Regex.Replace(m1.Groups["title"].Value, @"\s+", " ", RegexOptions.IgnoreCase);
                if (!string.IsNullOrEmpty(Title))
                  SiteNameText.Text = Title;
              }
              else SiteNameText.Text = string.Empty;
            }
            Match m2 = Regex.Match(PageData, @"description""\scontent=""(?<desc>[^""]*)""", RegexOptions.IgnoreCase);
            if (m2.Groups["desc"].Success)
            {
              Desc = Regex.Replace(m2.Groups["desc"].Value, @"\s+", " ", RegexOptions.IgnoreCase);
              if (!string.IsNullOrEmpty(Desc))
                SiteDescriptionText.Text = Desc;
            }
            else SiteDescriptionText.Text = string.Empty;
            Match m3 = Regex.Match(PageData, @"image""\scontent=""(?<image>[^""]*)""", RegexOptions.IgnoreCase);
            if (m3.Groups["image"].Success)
            {
              Image = m3.Groups["image"].Value;
              if (!string.IsNullOrEmpty(Image))
                SitePicture.ImageLocation = Image;
            }
            Match m5 = Regex.Match(PageData, @"url""\scontent=""(?<url>[^""]*)""", RegexOptions.IgnoreCase);
            if (m5.Groups["url"].Success)
            {
              BaseUrl = Regex.Replace(m5.Groups["url"].Value, @"\s+", " ", RegexOptions.IgnoreCase);
              if (!string.IsNullOrEmpty(BaseUrl))
                SiteUrlText.Text = BaseUrl;
            }
          }
          catch
          {

          }
        Cursor.Current = Cursors.Default;
      }
    }

    private void TestSiteRegex_Click(object sender, EventArgs e)
    {
      ResultsViewText.Controls.Clear();
      string webData = Util.GetWebData(Util.ResovedUrl);
      SourceViewText.Text = webData;
      try
      {
        Match m = Regex.Match(webData, RegexDesignerText.Text, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        if (m.Groups["title"].Success && m.Groups["url"].Success)
        {
          ResultsViewText.Controls.Clear();
          while (m.Success)
          {
            ResultsViewText.Controls.Add(CreateButton(m.Groups["title"].Value, m.Groups["imageUrl"].Value, sender));
            m = m.NextMatch();
          }
          ResultsViewText.BringToFront();
        }
        else if (m.Groups["file"].Success)
        {
          string baseGameUrl = GameBaseUrlText.Text;
          if (string.IsNullOrEmpty(baseGameUrl))
            baseGameUrl = SiteUrlText.Text;
          PlayerPlay(Util.ResolvedUrl(m.Groups["file"].Value, baseGameUrl));
        }
      }
      catch (Exception ex)
      {
        string message = ex.Message;
      }
    }

    private void InsertSelectorOptions()
    {
      InsertRegexSelector.DataSource = new BindingSource(Util.RegexGroupOptions(), null);
      InsertRegexSelector.DisplayMember = "Key";
      InsertRegexSelector.ValueMember = "Value";
    }

    private void ButtonInsert_Click(object sender, EventArgs e)
    {
      int selectedStart = RegexDesignerText.SelectionStart;
      int selectedLength = RegexDesignerText.SelectionLength;
      string replaceString = InsertRegexSelector.SelectedValue.ToString();
      if (selectedLength != 0)
      {
        string newstring = replaceString.Replace("@", RegexDesignerText.Text.Substring(selectedStart + selectedLength, 1));
        RegexDesignerText.SelectedText = newstring;
      }
      else RegexDesignerText.Text = RegexDesignerText.Text.Insert(selectedStart, replaceString);

    }

    private void CopySelected_Click(object sender, EventArgs e)
    {
      string newText = SourceViewText.SelectedText.Replace("\n", @"\s*").Replace(" ", @"\s").Replace("\r", "");
      newText = newText.Replace(@"[", @"\[");
      newText = newText.Replace(@"]", @"\]");
      //if (string.IsNullOrEmpty(RegexDesignerText.SelectedText))
      RegexDesignerText.Text = RegexDesignerText.Text.Insert(RegexDesignerText.SelectionStart, SourceViewText.SelectedText.Replace("\n", @"\s*").Replace(" ", @"\s").Replace("\r", ""));
      //    else RegexDesignerText.SelectedText = newText;
    }

    private void SitePicture_Click(object sender, EventArgs e)
    {
      GetFileDialog.InitialDirectory = @"Libraries\Pictures";
      DialogResult result = GetFileDialog.ShowDialog();
      if (result == DialogResult.OK)
      {
        SitePicture.ImageLocation = Path.GetFullPath(GetFileDialog.FileName);
      }
    }

    private void DoneRegexButton_Click(object sender, EventArgs e)
    {
      if (SelectedTextBox != null)
        SelectedTextBox.Text = RegexDesignerText.Text;
      RegexDesignerText.BackColor = Color.White;
      DesignerPanel.Enabled = false;
    }

    private void CancelButton_Click(object sender, EventArgs e)
    {
      RegexDesignerText.BackColor = Color.White;
      SelectedTextBox.BackColor = Color.White;
      RegexDesignerText.Clear();
      SelectedTextBox = null;
      RegexDesigner.Text = "Regex Desinger";
      DesignerPanel.Enabled = false;
    }

    private void ViewsWindowSwitch_Click(object sender, EventArgs e)
    {
      if (sender.Equals(HtmlViewButton))
      {
        HtmlViewText.BringToFront();
      }
      else if (sender.Equals(SourceViewButton))
      {
        string webData = Util.GetWebData(Util.ResovedUrl);
        SourceViewText.Text = webData;
        SourceViewText.BringToFront();
      }
      else if (sender.Equals(ResultsViewButton))
        ResultsViewText.BringToFront();
    }

    public Button CreateButton(string Text, string ImageUrl, object selected)
    {

      Button newButton = new Button();
      newButton.Text = Text;
      newButton.BackgroundImage = Bitmap.FromFile(@"C:\ProgramData\Team MediaPortal\MediaPortal\skin\DefaultWide\Media\icon_empty_nofocus1.png");
      newButton.Size = new System.Drawing.Size(110, 60);
      newButton.ImageAlign = ContentAlignment.MiddleCenter;
      newButton.BackColor = Color.Gray;
      newButton.BackgroundImageLayout = ImageLayout.Stretch;
      newButton.FlatStyle = FlatStyle.Popup;
      newButton.FlatAppearance.CheckedBackColor = Color.DarkBlue;
      newButton.FlatAppearance.BorderSize = 20;
      newButton.FlatAppearance.MouseOverBackColor = Color.DarkRed;
      newButton.Tag = selected;
      newButton.TextImageRelation = TextImageRelation.ImageAboveText;

      newButton.Click += new EventHandler(DynamicButton_Click);

      return newButton;
    }

    protected void DynamicButton_Click(object sender, EventArgs e)
    {
      LoadResultsView(sender);
    }

    protected void LoadResultsView(object sender)
    {
      Cursor.Current = Cursors.WaitCursor;
       
      if (sender == null)
      {
        return;
      }
      if (sender.GetType() == typeof(Button))
      {
        Button button = (Button)sender;
        SelectedObject = button.Tag; 
        
      }
      else SelectedObject = sender;
        
      if (SelectedObject.GetType() == typeof(Site))
      {
        Site site = (Site)SelectedObject;
        HtmlViewText.Navigate(Util.ResolvedUrl(SiteUrlText.Text,""));
        ResultsViewText.Controls.Clear();
        foreach (Object Item in flashGames.GetNext(SelectedObject))
        {
          if (Item.GetType() == typeof(Category))
          {
            Category category = (Category)Item;
            ResultsViewText.Controls.Add(CreateButton(category.Name, category.ImageUrl, category));
          }
          else if (Item.GetType() == typeof(Game))
          {
            Game game = (Game)Item;
            ResultsViewText.Controls.Add(CreateButton(game.Name, game.ImageUrl, game));
          }
        }
        ResultsViewText.BringToFront();
      }
      else if (SelectedObject.GetType() == typeof(Category))
      {
        Category cat = (Category)SelectedObject;
        HtmlViewText.Navigate(Util.ResolvedUrl(cat.Url,SiteUrlText.Text));
        ResultsViewText.Controls.Clear();
        foreach (Object Item in flashGames.GetNext(SelectedObject))
        {
          if (Item.GetType() == typeof(Category))
          {
            Category category = (Category)Item;
            ResultsViewText.Controls.Add(CreateButton(category.Name, category.ImageUrl, category));
          }
          else
          {
            Game game = (Game)Item;
            ResultsViewText.Controls.Add(CreateButton(game.Name, game.ImageUrl, game));
          }
        }
        ResultsViewText.BringToFront();
      }
      else if (SelectedObject.GetType() == typeof(Game))
      {
        Game game = (Game)SelectedObject;
        HtmlViewText.Navigate(Util.ResolvedUrl(game.Url, SiteUrlText.Text));
        if (!string.IsNullOrEmpty(GameFileRegexText.Text))
        {
          game.LoadGame();
          PlayerPlay(game.FileUrl);
        }
      }
      
      Cursor.Current = Cursors.Default;
    }

    private void SiteSaveButton_Click(object sender, EventArgs e)
    {
      Cursor.Current = Cursors.WaitCursor;
      if (DoSiteVailidationChecK())
      {
        SelectedSite.Name = SiteNameText.Text;
        SelectedSite.Url = SiteUrlText.Text;
        SelectedSite.ImageUrl = SitePicture.ImageLocation;
        SelectedSite.Description = SiteDescriptionText.Text;
        SelectedSite.CategoryRegex = CategoryRegexText.Text;
        SelectedSite.SubCategoryRegex = SubCategoryRegexText.Text;
        SelectedSite.GameRegex = GameRegexText.Text;
        SelectedSite.GameFileRegex = GameFileRegexText.Text;
        SelectedSite.GameBaseUrl = GameBaseUrlText.Text;
        flashGames.SaveSite(SelectedSite);
        GetSiteList();
        SiteSelectButton.SelectedIndex = SiteSelectButton.Items.Count - 1;
        HtmlViewText.AllowNavigation = true;
        HtmlViewText.Navigate(Util.ResolvedUrl(SelectedSite.Url,""));
        LoadResultsView(SelectedSite);
      }
      Cursor.Current = Cursors.Default;
    }

    public void GetSiteList()
    {
      Site site = new Site();
      List<Site> Sites = new List<Site>(flashGames.GetSiteList());
      site.Name = "Create New Site";
      Sites.Insert(0, site);
      SiteSelectButton.DataSource = new BindingSource(Sites, null);
    }

    private void SiteDeleteButton_Click(object sender, EventArgs e)
    {
      if (SiteSelectButton.SelectedItem.ToString() != "Create New Site")
      {
        flashGames.DeleteSite((Site)SiteSelectButton.SelectedItem);
        GetSiteList();
      }
    }

    private void SiteSelectButton_SelectedIndexChanged(object sender, EventArgs e)
    {
      SelectedSite = (Site)SiteSelectButton.SelectedItem;
      SiteSelectButton.Tag = SelectedSite;
      flashGames.LoadSite(SelectedSite);
      LoadSite();
    }

    public void LoadSite()
    {
      Cursor.Current = Cursors.WaitCursor;
      SitePicture.ImageLocation = SelectedSite.ImageUrl;
      SiteNameText.Text = SelectedSite.Name;
      SiteUrlText.Text = SelectedSite.Url;
      SiteDescriptionText.Text = SelectedSite.Description;
      CategoryRegexText.Text = SelectedSite.CategoryRegex;
      SubCategoryRegexText.Text = SelectedSite.SubCategoryRegex;
      GameRegexText.Text = SelectedSite.GameRegex;
      GameFileRegexText.Text = SelectedSite.GameFileRegex;
      GameBaseUrlText.Text = SelectedSite.GameBaseUrl;
      ResultsViewText.Controls.Clear();
      if (SelectedSite.Name != "Create New Site")
      {
        HtmlViewText.AllowNavigation = true;
        HtmlViewText.Navigate(Util.ResolvedUrl(SelectedSite.Url,""));
        LoadResultsView(SelectedSite);
      }
      ResultsViewText.BringToFront();
      Cursor.Current = Cursors.Default;

    }

    private void PlayerButton_Click(object sender, EventArgs e)
    {
      ResultsViewText.SendToBack();
      SourceViewText.SendToBack();
      HtmlViewText.SendToBack();
    }

    private void BackButton_Click(object sender, EventArgs e)
    {
      
      if (SelectedObject == null)
      {
        return;
      }
      else if (SelectedObject.GetType() == typeof(Site))
      {
        ResultsViewText.Controls.Clear();
        foreach (Object Item in flashGames.GetLast(ref SelectedObject))
        {
          Site site = (Site)Item;
          ResultsViewText.Controls.Add(CreateButton(site.Name, site.ImageUrl, site));
        }
      }
      else if (SelectedObject.GetType() == typeof(Category))
      {
        ResultsViewText.Controls.Clear();
        foreach (Object Item in flashGames.GetLast(ref SelectedObject))
        {
          Category category = (Category)Item;
          ResultsViewText.Controls.Add(CreateButton(category.Name, category.ImageUrl, category));
        }
      }
      else if (SelectedObject.GetType() == typeof(Game))
      {
        ResultsViewText.Controls.Clear();
        foreach (Object Item in flashGames.GetLast(ref SelectedObject))
        {
          Category category = (Category)Item;
          ResultsViewText.Controls.Add(CreateButton(category.Name, category.ImageUrl, category));
        }
      }
      if (player != null) player.Dispose();
      ResultsViewText.BringToFront();
    }

    private void RegexTextBox_Click(object sender, EventArgs e)
    {
      TextBox textBox = (TextBox)sender;
      RegexDesignerText.Text = textBox.Text;
      if (SelectedTextBox != null)
        SelectedTextBox.BackColor = Color.White;
      SelectedTextBox = textBox;
      SelectedTextBox.BackColor = Color.Turquoise;
      RegexDesignerText.BackColor = SelectedTextBox.BackColor;
      DesignerPanel.Enabled = true;
    }

    public void PlayerPlay(string Url)
    {
      if (string.IsNullOrEmpty(Url))
        MessageBox.Show("Unable to play no Url");
      else if (Url.ToLower().Contains("unity") || Url.ToLower().Contains("swf"))
      {
        player = new FlashUnityPlayer.Player();
        player.PlayerWindow = FlashUnityPlayer.Player.FlashUnityWindow.Fullscreen;
        DesignViewsPanel.Controls.Add(player);
        player.BringToFront();
        player.Play(Url);
      }
      else MessageBox.Show("Unable to play file");
    }

    void gamePlayer_FormClosing(object sender, FormClosingEventArgs e)
    {
      ResultsViewText.BringToFront();
    }

    private void StopButton_Click(object sender, EventArgs e)
    {
      player.Dispose();
    }

    private void OpenFileDialogBtn_Click(object sender, EventArgs e)
    {
      DialogResult result = folderBrowserDialog1.ShowDialog();
      if (result == DialogResult.OK)
      {
        GameFolderText.Text = folderBrowserDialog1.SelectedPath;
      }
    }

    private void GameFolderSaveBtn_Click(object sender, EventArgs e)
    {
      flashGames.GameFolderPath = GameFolderText.Text;
    }

  }

  public class Item
  {
    public string Text { get; set; }
    public string Value { get; set; }

    public Item(string text, string value)
    {
      Text = text;
      Value = value;
    }

    public override string ToString()
    {
      return Value;
    }
  }
}
